<?php
namespace Admin\Controller;
use Lib\Controller\AdminBaseController;
use Think\Upload;

use Payment\Common\PayException;
use Payment\Client\Refund;
use Payment\Client\Query;
use Payment\Config;
use Payment\Common\WxConfig;

class OrdersController extends AdminBaseController{

    private $videoBookModel;
    private $ProvinceModel;
    private $CityModel;
    private $HospitalModel;
    private $videoBookInfoModel;

    public function __construct(){
        $this->videoBookInfoModel = D('videoBookInfo');
        $this->videoBookModel   = D('VideoBook');
        $this->ProvinceModel    = D('Province');
        $this->CityModel        = D('City');
        $this->HospitalModel    = D('Hospital');
        parent::__construct();
    }

    /**
     * [unicode2utf8  【转码】
     * 字符串转码 无论是什么文件名称，先unicode转utf8 unicode转utf8 注意$str='"..."'，内部双引号，外部单引号 对于变量$str='..'，我们需要处理'"'.$str.'"',处理后成一个新变量]
     * @author xiezy
     * @date   2018-06-07
     * @param  [type]     $str [description]
     * @return [type]          [description]
     */
    public function unicode2utf8($str){
       if(!$str) return $str;
       $decode = json_decode($str);
       if($decode) return $decode;
       $str = '["' . $str . '"]';
       $decode = json_decode($str);
       if(count($decode) == 1){
           return $decode[0];
       }
       return $str;
    }
    
    public function make_list(){
        if(session('roleId') != '3'){
            echo '该页面是 角色为：剪辑 的管理员使用页面';
        }else{
            $where['maker_id'] = session('adminId');
            

            switch(I('order_find')){
                case 0 :
                    $condition = 'ordersn';
                    break;
                case 1 :
                    $condition = 'parents_phone';
                default:
                    break;
            }
            $orderNo = I('keywords',null,'string');
            if($condition=='ordersn'){
                if (trim($orderNo) != null) {
                    $where['vb.ordersn'] = array('like','%'.$orderNo.'%');
                }
            }
            else if($condition=='parents_phone'){
                $where['vb.parents_phone'] = array('like','%'.$orderNo.'%');
            }
            
            switch (I('search')){
                case 1 :
                    $where['vb.is_make'] = 0;
                    $where['vbi.material_video_0']      = array('neq','');
                    break;
                case 2 :
                    $where['vb.is_make'] = 1;
                    break;
                case 3 :
                    $where['vb.is_make'] = 2;
                    break;
                case 0 :
                    $where['vb.is_make'] = array('gt','-99');
                    break;
                default:
                    break;
            }
            
            //获取订单数量
            $ordersNum = $this->videoBookModel->getOrdersCount($where);
            //分页
            $p     = I('get.p',1);
            $page  = new \Lib\ORG\Page($ordersNum);
            $limit = $page->listRows;
            $pageString  = $p.','. $limit;
            $orderList = $this->videoBookModel->getOrderList($page,$where,$pageString);
            
            foreach($orderList as $key =>$val){
                if(isset($val['projectid'])){
                    $orderList[$key]['project_name']    = '宝宝出生视频服务';
                }
                if(isset($val['provinceid'])){
                    $province_name = $this->ProvinceModel->where('ProvinceID = '.$val['provinceid'])->getField('ProvinceName');
                    $orderList[$key]['province_name']   = $province_name;
                }
                if(isset($val['cityid'])){
                    $city_name = $this->CityModel->where('CityID = '.$val['cityid'])->getField('CityName');
                    $orderList[$key]['city_name']       = $city_name;
                }
                if(isset($val['hospitalid'])){
                    $hospital_name = $this->HospitalModel->where('id = '.$val['hospitalid'])->getField('hospital_name');
                    $orderList[$key]['hospital_name']       = $hospital_name;
                }
            }
            
            //输出
            if ($orderList) {
                $this->assign('orderList', $orderList );
            }
            
            $this->assign('page', $page->show());
            $this->display();
        }
    }

    /**
     * 订单列表
     */
    public function orders_list() {
        if(session('roleId') == '1'){
            $where = null;
        }
        elseif(session('roleId') == '5'){
            $cityString = cookie('agentData')['city_id'];
            $cityList = explode(',', $cityString);
            $where['_string'] = '';
            foreach($cityList as $clkey => $clval){
                if($where['_string'] == ''){
                    $where['_string'] = 'cityID = '.$clval;
                }else{
                    $where['_string'] = 'cityID = '.$clval . ' or ' .$where['_string'];
                }
            }
        }
        
        switch(I('order_find')){
            case 0 :
                $condition = 'ordersn';
                break;
            case 1 :
                $condition = 'parents_phone';
            default:
                break;
        }
        $orderNo = I('keywords',null,'string');
        if($condition=='ordersn'){
            if (trim($orderNo) != null) {
                $where['vb.ordersn'] = array('like','%'.$orderNo.'%');
            }
        }
        else if($condition=='parents_phone'){
            $where['vb.parents_phone'] = array('like','%'.$orderNo.'%');
        }

        switch (I('search')){
            case 1 :
                $where['vb.is_make'] = 0;
                $where['vbi.material_video_0']      = array('neq','');
                break;
            case 2 :
                $where['vb.is_make'] = 1;
                break;
            case 3 :
                $where['vb.is_make'] = 2;
                break;
            case 0 :
                $where['vb.is_make'] = array('gt','-99');
                break;
            default:
                break;
        }
        
        $where['maker_id'] = 0;
        //获取订单数量
        $ordersNum = $this->videoBookModel->getOrdersCount($where);
        
        //分页
        $p     = I('get.p',1);
        $page  = new \Lib\ORG\Page($ordersNum);
        $limit = $page->listRows;
        $pageString  = $p.','. $limit;
        $orderList = $this->videoBookModel->getOrderList($page,$where,$pageString);

        foreach($orderList as $key =>$val){
            if(isset($val['projectid'])){
                $orderList[$key]['project_name']    = '宝宝出生视频服务';
            }
            if(isset($val['provinceid'])){
                $province_name = $this->ProvinceModel->where('ProvinceID = '.$val['provinceid'])->getField('ProvinceName');
                $orderList[$key]['province_name']   = $province_name;
            }
            if(isset($val['cityid'])){
                $city_name = $this->CityModel->where('CityID = '.$val['cityid'])->getField('CityName');
                $orderList[$key]['city_name']       = $city_name;
            }
            if(isset($val['hospitalid'])){
                $hospital_name = $this->HospitalModel->where('id = '.$val['hospitalid'])->getField('hospital_name');
                $orderList[$key]['hospital_name']       = $hospital_name;
            }
        }

        //输出
        if ($orderList) {
            $this->assign('orderList', $orderList );
        }

        $this->assign('page', $page->show());
        $this->display();
    }

    /**
     * 查看订单详情
     */
    public function order_details(){
        if (IS_GET) {
            $where['vb.id'] = I('get.id',0,'int');
            if ($where['vb.id'] <= 0) {
                //订单ID错误
                $this->redirect(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
            }

            $orderInfo =  $this->videoBookModel->getOrderList($page='',$where,$p=null,$type="find");
            if(isset($orderInfo['projectid'])){
                $orderInfo['project_name']    = '宝宝出生视频服务';
            }
            if(isset($orderInfo['provinceid'])){
                $province_name = $this->ProvinceModel->where('ProvinceID = '.$orderInfo['provinceid'])->getField('ProvinceName');
                $orderInfo['province_name']   = $province_name;
            }
            if(isset($orderInfo['cityid'])){
                $city_name = $this->CityModel->where('CityID = '.$orderInfo['cityid'])->getField('CityName');
                $orderInfo['city_name']       = $city_name;
            }
            if(isset($orderInfo['hospitalid'])){
                $hospital_name = $this->HospitalModel->where('id = '.$orderInfo['hospitalid'])->getField('hospital_name');
                $orderInfo['hospital_name']       = $hospital_name;
            }
            //视频路径
            for($j = 0;$j <= 3;$j++){
                if($orderInfo['material_video_'.$j] != null){
                    $arrr[$j] = array($j=>$orderInfo['material_video_'.$j]);
                }
            }
            if(isset($arrr)){
                foreach($arrr as $key =>$val){
                    foreach($val as $k => $v){
                        $orderInfo['video_arr'][$key] = $v;
                    }
                    $orderInfo['video_num'] = $key+1;
                }
            }
            //图片路径
            for($i = 0;$i <= 19;$i++){
                if($orderInfo['video_material_img_'.$i] != null){
                    $arr[$i] = array($i=>$orderInfo['video_material_img_'.$i]);
                    $imgZipfilenameArr[$i] = array($i=>$orderInfo['video_material_img_'.$i]);
                }
            }
            if(isset($arr)){
                foreach($arr as $key =>$val){
                    foreach($val as $k => $v){
                        $orderInfo['img_arr'][$key] = $v;
                    }
                    $orderInfo['img_num'] = $key+1;
                }
            }else{
                $orderInfo['img_num'] = 0;
            }

            $this->assign('info',$orderInfo);
            $this->display('edit_orders');
        }
    }

    /**
     * [download_img_zip 打包下载压缩包]
     * @author lin
     * @date   2018-06-07
     * @return [type]     [description]
     */
    public function download_img_zip(){
        $where['ordersn'] = I('get.ordersn');
        $orderInfo =  $this->videoBookInfoModel->where($where)->find();
        //图片路径
        for($i = 0;$i <= 19;$i++){
            if($orderInfo['video_material_img_'.$i] != null){
                $imgfilenameArr[$i] = './upload/'.$orderInfo['video_material_img_'.$i];
            }
        }
        //视频路径
        for($j = 0;$j <= 4;$j++){
            if($orderInfo['material_video_'.$j] != null){
                $videofilenameArr[$j] = './upload/'.$orderInfo['material_video_'.$j];
            }
            if($j == 4 && $orderInfo['material_video_c'] != ''){
                $videofilenameArr[$j+1] = './upload/'.$orderInfo['material_video_c'];
            }
        }
//         $zipfilenameArr = array_merge($imgfilenameArr,$videofilenameArr);
// //         p($orderInfo);
//         p($imgfilenameArr);p($videofilenameArr);return;
        
        $imgZipfilename = "./upload/" . $orderInfo['ordersn'] . ".zip"; // 最终生成的文件名（含路径）
        // 生成文件
        $zip = new \ZipArchive(); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if ($zip->open ( $imgZipfilename, \ZIPARCHIVE::CREATE ) !== TRUE) {
            exit ( '无法打开文件，或者文件创建失败' );
        }

        //$zipfilenameArr 就是一个存储文件路径的数组 比如 array('/a/1.jpg,/a/2.jpg....');
//         foreach ( $zipfilenameArr as $val ) {
//             $zip->addFile ( $val, basename ( $val ) ); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
//         }
        //将不同类型的文件分开不同的目录进行压缩↓
        foreach ( $imgfilenameArr as $val ) {
            $zip->addFile ( $val, '/img/'.basename ( $val ) ); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
        foreach ( $videofilenameArr as $vv ) {
            $zip->addFile ( $vv, '/video/'.basename ( $vv ) ); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
        $zip->close (); // 关闭

        //下面是输出下载;
        header ( "Cache-Control: max-age=0" );
        header ( "Content-Description: File Transfer" );
        header ( 'Content-disposition: attachment; filename=' . basename ( $imgZipfilename ) ); // 文件名
        header ( "Content-Type: application/zip" ); // zip格式的
        header ( "Content-Transfer-Encoding: binary" ); // 告诉浏览器，这是二进制文件
        header ( 'Content-Length: ' . filesize ( $imgZipfilename ) ); // 告诉浏览器，文件大小
        @readfile ( $imgZipfilename );//输出文件;

        $this->assign('imgZipDownUrl',$imgZipfilename);
    }

    /**
     * [empty_function 空方法用于ajax请求]
     * @author xiezy
     * @date   2018-05-14
     * @return [type]     [description]
     */
    public function empty_function(){
        $returndata['status'] = 1;
        $this->ajaxReturn($returndata);
    }

    /**
     * [save_order_info 后台保存完善信息]
     * 【上传宝宝视频】最终版
     * @author xiezy
     * @date   2018-05-14
     * @return [type]     [description]
     */
    public function save_order_info(){
        //订单号作为查询条件
        $whereId['id'] = I('post.id');
        $where['ordersn'] = $this->videoBookModel->where($whereId)->getField('ordersn');

        $vbInfo = $this->videoBookInfoModel->where($where)->find();

        //上传图片的配置
        $config = array(
            'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
            'exts' => array('mp4', 'flv', 'avi'),// 设置附件上传类型
            'subName' => array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
            'saveName'   =>    array('uniqid',''),
            'savePath' => C('UPLOAD_VIDEO_FINAL_PATH'), //保存路径
            'rootPath' => './Upload/',
            'autoSub'    =>    true,
        );
        $this->uploader = new Upload($config, 'Local');
        $info = $this->uploader->upload($_FILES);
        if(!$info){//提示错误信息
            $returndata ['status'] = 0; // 状态
            $returndata ['info'] = $this->uploader->getError();
            $this->ajaxReturn($returndata);
        }else{
            //最终视频--路径
            $saveBookInfoImgDate['video_final'] = $info['upload_babyvideo']['savepath'] . $info['upload_babyvideo']['savename'];
            //删除原视频素材
            for($j = 0;$j <= 3;$j++){
                if($vbInfo['material_video_'.$j] != null){
                    $imgUrl = 'upload/'.$vbInfo['material_video_'.$j];
                    unlink($imgUrl);
                    $saveBookInfoImgDate['material_video_'.$j] = '';
                }
            }
            for($i = 0;$i <= 19;$i++){
                if($vbInfo['video_material_img_'.$i] != null){
                    $videoUrl = 'upload/'.$vbInfo['video_material_img_'.$j];
                    unlink($videoUrl);
                    $saveBookInfoImgDate['video_material_img_'.$j] = '';
                }
            }
            //设置视频提取码
            $arr = array_merge(range(0, 9), range('a', 'z'));
            $str = '';
            $arr_len = count($arr);
            for ($i = 0; $i < 6; $i++)
            {
                $rand = mt_rand(0, $arr_len-1);
                $str.=$arr[$rand];
            }
            $saveGetVideoNumDate['is_make']       = 2;      //制作状态：制作完成（2）
            $saveGetVideoNumDate['get_video_num'] = $str;   //视频提取码
            $saveGetVideoNumResult = $this->videoBookModel->where($where)->save($saveGetVideoNumDate);
            $uploadResult = $this->videoBookInfoModel->where($where)->save($saveBookInfoImgDate);
            if($uploadResult!==false){
                $returndata['status'] = 1;
                $returndata['info']   = '上传成功';
                $returndata['url']    = U(MODULE_NAME.'/orders/order_details',array('id'=>$where['id']));
                $this->ajaxReturn($returndata);
            }else{
                $returndata['status'] = 0;
                $returndata['info']   = '上传失败';
                $this->ajaxReturn($returndata);
            }
        }


    }

    /**
     * [webloadForOrder 后台保存完善信息]
     * 【上传宝宝视频】最终版
     * @author xiezy
     * @date   2018-06--7
     * @return [type]     [description]
     */
    public function webloadForOrder(){
        //订单号作为查询条件
        $whereId['id'] = I('order_id');
        $where['ordersn'] = $this->videoBookModel->where($whereId)->getField('ordersn');

        $vbInfo = $this->videoBookInfoModel->where($where)->find();

        // Make sure file is not cached (as it happens for example on iOS devices)
        header("Access-Control-Allow-origin:*");
        //header("Access-Control-Allow-Credentials:true");
        //header('Access-Control-Allow-Headers:x-requested-with,content-type');
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }

        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // var_dump($_REQUEST);
        //
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // $targetDir = './Upload/upload_tmp';
        // $uploadDir = './Upload/upload';
        $ordersnDir     = $where["ordersn"].'/'.date("Y-m-d",time());
        $targetDir      = './Upload/upload_tmp';
        $uploadDir      = './Upload/baby_video_final/'.$ordersnDir;
        $video_final    = 'baby_video_final/'.$ordersnDir;

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge       = 5 * 3600; // Temp file age in seconds   临时文件允许存在的最大时间

        // 创建目录--临时目录
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // 创建目录--最终目录
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir,0777,true);
        }

        // Get a file name  获取文件名
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        //-------------------------------------------------------
        $fileName= $this->unicode2utf8('"'.$fileName.'"');
        $fileName= iconv("UTF-8", "GBK", $fileName);//防止fopen语句失效
        //-----------------------------------------------------------------------

        $filePath   = $targetDir . DIRECTORY_SEPARATOR . $fileName;     //临时文件路径
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;    //文件上传最终路径

        // Chunking might be enabled
        // 可以分割
        $chunk  = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        // Remove old temp files
        if ($cleanupTargetDir) {
            //判断是否为临时目录，且可否授权打开。
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                // 如果临时文件是当前文件，则进入下一个文件
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                // 删除临时文件，如果它大于最大年龄，而不是当前文件
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done  = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            $pathInfo = pathinfo($fileName);
            $hashStr = substr(md5($pathInfo['basename']),8,16);
            $hashName = time() . $hashStr . '.' .$pathInfo['extension'];

            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;          //文件上传最终路径
            $video_final_path = $video_final. DIRECTORY_SEPARATOR .$hashName;   //用于存数据路径

            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
            //插入数据库-------------------------------------------------------------------------------------
            //最终视频--路径
            $saveBookInfoImgDate['video_final'] = $video_final_path;
            //删除原视频素材
            for($j = 0;$j <= 3;$j++){
                if($vbInfo['material_video_'.$j] != null){
                    $imgUrl = 'upload/'.$vbInfo['material_video_'.$j];
                    unlink($imgUrl);
                    $saveBookInfoImgDate['material_video_'.$j] = '';
                }
            }
            //删除图片素材
            for($i = 0;$i <= 19;$i++){
                if($vbInfo['video_material_img_'.$i] != null){
                    $videoUrl = 'upload/'.$vbInfo['video_material_img_'.$i];
                    unlink($videoUrl);
                    $saveBookInfoImgDate['video_material_img_'.$i] = '';
                }
            }
            //设置视频提取码
            $arr = array_merge(range(0, 9), range('a', 'z'));
            $str = '';
            $arr_len = count($arr);
            for ($i = 0; $i < 6; $i++)
            {
                $rand = mt_rand(0, $arr_len-1);
                $str.=$arr[$rand];
            }
            $saveGetVideoNumDate['is_make']       = 2;      //制作状态：制作完成（2）
            $saveGetVideoNumDate['get_video_num'] = $str;   //视频提取码
            $saveGetVideoNumResult = $this->videoBookModel->where($where)->save($saveGetVideoNumDate);
            $uploadResult = $this->videoBookInfoModel->where($where)->save($saveBookInfoImgDate);
            if($uploadResult!==false){
                $returndata['status'] = 1;
                $returndata['info']   = '上传成功';
                $returndata['url']    = U(MODULE_NAME.'/orders/order_details',array('id'=>$where['id']));
            }else{
                $returndata['status'] = 0;
                $returndata['info']   = '上传失败';
            }
            //返回数据
            echo json_encode($returndata);
            die;
            //插入数据库-------------------------------------------------------------------------------------
        }

        // Return Success JSON-RPC response
        // die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    /**
     * [startMake 开始制作]
     * @author xiezy
     * @date   2018-05-14
     * @return [type]     [description]
     */
    public function startMake(){
        if(session('roleId') != '3'){
            $data['info'] = '暂无权限';
            $data['status'] = 0;
            $this->ajaxReturn($data);
        }else{
            $where['id'] = I('post.id');
            
            $checkOrder = $this->videoBookModel->where($where)->find();
            
            if($checkOrder['maker_id'] != '0'){
                $data['url'] = U(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
                $data['info'] = '该订单已被选择';
                $data['status'] = 0;
                $this->ajaxReturn($data);
            }else{
                $savedata['is_make'] = 1; //制作中
                $savedata['maker_id'] = session('adminId');
                $this->videoBookModel->where($where)->save($savedata);
                $data['url'] = U(MODULE_NAME.'/'.CONTROLLER_NAME.'/orders_list');
                $data['info'] = '已选择该订单';//该视频制作中';
                $data['status'] = 1;
                $this->ajaxReturn($data);
            }
            
        }
    }

    /**
     * [put_out_excel 根据订单--导出excel表格]
     * @author xiezy
     * @date   2018-06-07
     * @return [type]     [description]
     */
    public function put_out_excel(){
        $orderList = $this->videoBookModel->select();
        foreach($orderList as$key=>$val){
            $orderList[$key]['info'] = $this->videoBookInfoModel->where('ordersn ='.$val['ordersn'])->find();
            $orderList[$key]['province_name'] = $this->ProvinceModel->where('ProvinceID = '.$val['provinceid'])->getField('ProvinceName');
            $orderList[$key]['city_name'] =$this->CityModel->where('CityID = '.$val['cityid'])->getField('CityName');
            $orderList[$key]['hospital_name'] =$this->HospitalModel->where('id = '.$val['hospitalid'])->getField('hospital_name');
        }

        require_once APP_PATH.'Lib/phpexcel/PHPExcel.php';
//         require_once APP_PATH.'Lib/phpexcel/PHPExcel/IOFactory.php';
        //创建excel对象
        $excel = new \PHPExcel();
        //设置excel属性
        $excelObj = $excel -> getActiveSheet();
//         //设置名字
        $excelObj->setTitle('订单数据');
//         //设置excel的列。根据需求添加
        $letter = array('A','B','C','D','E','F','G','H','I','J');

        $fileheader = array('省市','医院','订单号','金额','宝宝身高(cm)','宝宝体重(kg)','出生日期','爸爸名字','妈妈名字','联系人手机');
        //设置表头name
        $excel->setActiveSheetIndex(0);

        //设置表头列的宽度
        $excelObj->getColumnDimension('A')->setWidth(20);
        $excelObj->getColumnDimension('B')->setWidth(35);
        $excelObj->getColumnDimension('C')->setWidth(50);
        $excelObj->getColumnDimension('D')->setWidth(15);
        $excelObj->getColumnDimension('E')->setWidth(15);
        $excelObj->getColumnDimension('F')->setWidth(15);
        $excelObj->getColumnDimension('G')->setWidth(20);
        $excelObj->getColumnDimension('H')->setWidth(20);
        $excelObj->getColumnDimension('I')->setWidth(20);
        $excelObj->getColumnDimension('J')->setWidth(30);

        //设置表头
        for($i = 0;$i < count($letter);$i++) {
            //单元宽度自适应,1.8.1版本phpexcel中文支持勉强可以，自适应后单独设置宽度无效
            //$objActSheet->getColumnDimension("$letter[$i]")->setAutoSize(true);
            //设置表头值，这里的setCellValue第二个参数不能使用iconv，否则excel中显示false
            $excelObj->setCellValue("$letter[$i]1",$fileheader[$i]);
            //设置表头字体样式
            $excelObj->getStyle("$letter[$i]1")->getFont()->setName('微软雅黑');
            //设置表头字体大小
            $excelObj->getStyle("$letter[$i]1")->getFont()->setSize(12);
            //设置表头字体是否加粗
            $excelObj->getStyle("$letter[$i]1")->getFont()->setBold(true);
            //设置表头文字垂直居中
            $excelObj->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置文字上下居中
            $excelObj->getStyle($letter[$i])->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //设置表头外的文字垂直居中
            $excel->setActiveSheetIndex(0)->getStyle($letter[$i])->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        }
        //对着列插入数据
        foreach($orderList as$k =>$v){
            $num = $k+2;
            $excel->setActiveSheetIndex(0);
            $excelObj->setCellValue('A'.$num, $v['province_name'].' '.$v['city_name']);
            $excelObj->setCellValue('B'.$num, $v['hospital_name']);
            $excelObj->setCellValue('C'.$num, ' '.$v['ordersn']);
            $excelObj->setCellValue('D'.$num, '￥'.$v['amount']);
            $excelObj->setCellValue('E'.$num, $v['info']['baby_height'] == '' ? '无' :$v['info']['baby_height']);
            $excelObj->setCellValue('F'.$num, $v['info']['baby_weight'] == '' ? '无' :$v['info']['baby_weight']);
            $excelObj->setCellValue('G'.$num, $v['info']['bron_time'] == '' ? '无' :date('Y-m-d H:i:s',$v['info']['bron_time']));
            $excelObj->setCellValue('H'.$num, $v['info']['father_name'] == '' ? '无' :$v['info']['father_name']);
            $excelObj->setCellValue('I'.$num, $v['info']['monther_name'] == '' ? '无' :$v['info']['monther_name']);
            $excelObj->setCellValue('J'.$num, $v['parents_phone']);
        }
        $excel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="report_'.time().'.xlsx"');
		header('Cache-Control: max-age=0');

		$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
		$objWriter->save('php://output');
		exit;
    }

}
?>
